<template>
  <div>
    <!--    查询功能-->
    <div style="margin-bottom: 5px">
      <!--    输入框-->
      <el-input v-model="name"
                @keyup.enter.native="loadPost"
                placeholder="请输入学院id"
                suffix-icon="el-icon-search"
                style="width: 200px;"></el-input>

      <!--      查询按钮-->
      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <!--      重置按钮-->
      <el-button type="success" @click="resetParam">重置</el-button>
      <!--      新增按钮-->
      <el-button type="primary" style="margin-left: 5px" @click="add" v-if="user.roleId!=2">新增</el-button>
    </div>

    <!--    列表展示-->
    <el-table :data="tableData"
              :header-cell-style="{background: '#D3D3D3FF',color:'#555555'}"
              highlight-current-row
              @current-change="selectCurrentChange"
    >
      
      <el-table-column prop="collegeId" label="学院id" width="160">
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="160" >
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" width="160" >
      </el-table-column>
      <el-table-column prop="id" label="专业id" width="160" >
      </el-table-column>
      <el-table-column prop="isDeleted" label="逻辑删除（0未删除、1已删除）" width="160">
      </el-table-column>
      <el-table-column prop=" name" label="专业名称">
      </el-table-column>
      <el-table-column prop="operate" label="操作"  v-if="user.roleId!=2">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="这是一段内容确定删除吗？"
              @confirm="del(scope.row.id)"
              style="margin-left: 5px"
          >
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--    分页  -->
    <div class="pagination-wrapper">
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

<!--    新增-->
    <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center
        :before-close="handleClose">
      <!--      表单-->
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="学院名称" prop="">
          <el-col :span="15">
            <el-select v-model="form.gmtCreate" placeholder="请选择学院">
              <el-option
                  v-for="item in Data"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="创建时间" prop="gmtCreate">
          <el-col :span="15">
            <el-select v-model="form.gmtCreate" placeholder="请选择时间">
              <el-option
                  v-for="item in StorageData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="更新时间" prop="gmtModified">
          <el-col :span="15">
            <el-select v-model="form.gmtModified" placeholder="请选择时间">
              <el-option
                  v-for="item in goodstypeData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="专业id" prop="id">
          <el-col :span="15">
            <el-input v-model="form.id"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="备注逻辑删除（0未删除、1已删除）" prop="isDeleted">
          <el-col :span="15">
            <el-input type="textarea" v-model="form.isDeleted"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="专业名称" prop="name">
          <el-col :span="15">
            <el-select v-model="form.gmtCreate" placeholder="请选择专业名称">
              <el-option
                  v-for="item in MajorData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
    </el-dialog>
<!--  出入库-->
    <el-dialog
        title="出入库"
        :visible.sync="inDialogVisible"
        width="30%"
        center
        :before-close="handleClose">
<!--        内层dialog-->
        <el-dialog
            width="50%"
            title="用户选择"
            :visible.sync="innerVisible"
            append-to-body>

          <SelectUser @doSelectUser="doSelectUser"></SelectUser>
          <span slot="footer" class="dialog-footer">
            <el-button @click="innerVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmUser">确 定</el-button>
          </span>
        </el-dialog>

      <!--      表单-->
      <el-form ref="formGoods" :rules="goodsrules" :model="formGoods" label-width="80px">
        <el-form-item label="物品名称">
          <el-col :span="15">
            <el-input v-model="formGoods.goodsname" readonly></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="申请人">
          <el-col :span="15">
            <el-input v-model="formGoods.username" readonly @click.native="selectUser"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="数量" prop="count">
          <el-col :span="15">
            <el-input v-model="formGoods.count"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-col :span="15">
            <el-input type="textarea" v-model="formGoods.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doInGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectUser from "@/components/user/SelectUser"
import {warehousing} from "@/api/Goods/warehousing";
import {del} from "@/api/Goods/Delete";
import {mod} from "@/api/Goods/Mod";
import {save} from "@/api/Goods/Save";
import {query} from "@/api/Goods/query";
import {queryStorage} from "@/api/Storage/queryStorage";
import {queryGoodsType} from "@/api/GoodsType/queryGoodsType";
export default {
  name: "GoodsManage",
  components: {SelectUser},
  data() {
    //数量规则
    let checkCount = (rule, value, callback) => {
      if (value > 9999) {
        callback(new Error('数量输入过大'))
      } else {
        callback();
      }
    }

    return {
      user: JSON.parse(sessionStorage.getItem('CurUser')),
      goodstypeData: [],
      StorageData: [],
      tableData: [],
      pageNum: 1,
      pageSize: 5,
      total: 0,
      name: '',
      storage: '',
      goodstype: '',
      centerDialogVisible: false,
      inDialogVisible: false,
      innerVisible: false,
      currentRow: {},
      tempUser: {},
      form: {
        id: '',
        name: '',
        storage: '',
        goodstype: '',
        count: '',
        remark: ''
      },
      formGoods: {
        goods: '',
        goodsname: '',
        count: '',
        userid: '',
        username: '',
        adminId: '',
        remark: '',
        action:'1',
      },
      goodsrules: {},
      rules: {
        name: [
          {required: true, message: '请输入物品名称', trigger: 'blur'}
        ],
        goodstype: [
          {required: true, message: '请输入选择分类', trigger: 'blur'}
        ],
        storage: [
          {required: true, message: '请输入选择仓库', trigger: 'blur'}
        ],
        count: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数字', trigger: 'blur'},
          {validator: checkCount, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    selectCurrentChange(val) {
      this.currentRow = val;
    },

    //展示类型列表
    formatGoodstype(row) {
      let temp = this.goodstypeData.find(item => {
        return item.id == row.goodstype
      })

      return temp && temp.name
    },
    //展示仓库列表
    formatStorage(row) {
      let temp = this.StorageData.find(item => {
        return item.id == row.storage
      })

      return temp && temp.name
    },
    //重置表单
    resetForm() {
      this.$refs.form.resetFields();
    },
    resetInForm() {
      this.$refs.formGoods.resetFields();
    },

    //新增功能
    add() {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.resetForm();

        this.form.id = ''
      })
    },

    //入库功能
    warehousing() {
      if (!this.currentRow.id) {
        this.$message({
          message: '请选择记录',
          type: 'warning'
        });
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm();
      })

      this.formGoods.goodsname = this.currentRow.name
      this.formGoods.goods = this.currentRow.id
      this.formGoods.adminId = this.user.id
      this.formGoods.action = 1
    },
    doInGoods() {
      warehousing(this.formGoods).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '入库成功',
            type: 'success'
          })
          this.inDialogVisible = false
          this.loadPost()
          this.resetInForm()
        } else {
          this.$message({
            message: '入库失败',
            type: 'error'
          })
        }
      })
    },
    selectUser() {
      this.innerVisible = true
    },
    confirmUser() {
      this.formGoods.username = this.tempUser.name
      this.formGoods.userid = this.tempUser.id
      this.innerVisible = false
    },
    doSelectUser(val) {
      console.log(val)
      this.tempUser = val

    },

    //出库功能
    outGoods() {
      if (!this.currentRow.id) {
        this.$message({
          message: '请选择记录',
          type: 'warning'
        });
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm();
      })

    this.formGoods.goodsname = this.currentRow.name
    this.formGoods.goods = this.currentRow.id
    this.formGoods.adminId = this.user.id
    this.formGoods.action = '2'
  },

    //修改功能
    mod(row){
      this.centerDialogVisible = true

      this.$nextTick(()=>{
        //赋值到表单
        this.form.id = row.id
        this.form.name = row.name
        this.form.storage = row.storage
        this.form.goodstype = row.goodstype
        this.form.count = row.count
        this.form.remark = row.remark
      })
    },
    //删除功能
    del(id){
      del(id).then(res=>{
        if (res.code === 200){
          this.$message({
            message:'删除成功',
            type:'success'
          })
          this.centerDialogVisible = false
          this.loadPost()
        }else{
          this.$message({
            message:'删除失败',
            type:'error'
          })
        }
      })
    },
    doMod(){
      mod(this.form).then(res=>{
        if (res.code === 200){
          this.$message({
            message:'修改成功',
            type:'success'
          })
          this.centerDialogVisible = false
          this.loadPost()
          this.resetForm()
        }else{
          this.$message({
            message:'修改失败',
            type:'error'
          })
        }
      })
    },
    doSave(){
     save(this.form).then(res=>{
        if (res.code === 200){
          this.$message({
            message:'增加成功',
            type:'success'
          })
          this.centerDialogVisible = false
          this.loadPost()
          this.resetForm()
        }else{
          this.$message({
            message:'增加失败',
            type:'error'
          })
        }
      })
    },
    //提交数据到后台
    save(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id){//如果有id则修改
            this.doMod();
          }else{//否则增加
            this.doSave();
          }
        } else {
          this.$message({
            message:'操作失败',
            type:'error'
          })
          return false;
        }
      });

    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
            this.formGoods.username=''
          })
          .catch(() => {});
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1
      this.pageSize = val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.loadPost()
    },
    resetParam(){
      this.name=''
      this.storage=''
      this.goodstype=''
      this.loadPost()
    },
    loadPost(){
      query({
        pageSize:this.pageSize,
        pageNum:this.pageNum,},
        {
          name:this.name,
          goodstype:this.goodstype+'',
          storage:this.storage+''
      }).then(res=>{
        if(res.code==200){
          this.tableData=res.data
          this.total=res.total
        }else{
          alert('获取数据失败')
        }

      })
    },
    //查询仓库
    loadStorage(){
      queryStorage().then(res=>{
        if (res.code === 200){
          this.StorageData=res.data
        }else{
          alert('获取数据失败')
        }
      })
    },
    //查询类型
    loadGoodstype(){
      queryGoodsType().then(res=>{
        if (res.code === 200){
          this.goodstypeData=res.data
        }else{
          alert('获取数据失败')
        }
      })
    },
  },
  beforeMount() {
    this.loadStorage()
    this.loadGoodstype()
    this.loadPost()
  }
}
</script>

<style scoped>
.pagination-wrapper {
  position: fixed;
  bottom: 0;
  width: 100%;
  /*background-color: #f5f5f5;*/
  padding: 10px 20px;
  /*box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);*/
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  max-width: 800px; /* 设置最大宽度以避免在大屏幕上过分拉伸 */
  margin: 0 30%; /* 居中显示分页组件 */
}
</style>